/*
 * Copyright (c) 2020 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package devlight.io.sample.view;

import devlight.io.library.LogUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.PageSliderProvider;

import java.util.ArrayList;
import java.util.List;

public class PageViewAdapter extends PageSliderProvider {

    private static final String TAG = PageViewAdapter.class.getCanonicalName();
    private AbilitySlice slice;
    private List<AbstractPageView> pageViews;
    public PageViewAdapter(AbilitySlice abilitySlice, List<AbstractPageView> list) {
        slice = abilitySlice;
        if (list != null) {
            pageViews = list;
            return;
        }
        pageViews = new ArrayList();
    }

    @Override
    public int getCount() {
        return this.pageViews.size();
    }

    @Override
    public String getPageTitle(int position) {
        List<AbstractPageView> abstractPageViews = (List<AbstractPageView>) pageViews;
        return abstractPageViews.get(position).getName();
    }

    @Override
    public Object createPageInContainer(ComponentContainer componentContainer, int i) {
        Component directionalLayout = new DirectionalLayout(slice);
        if (i >= 0 && i < this.pageViews.size()) {
            directionalLayout = pageViews.get(i).getRootView();
        }
        componentContainer.addComponent(directionalLayout);
        return directionalLayout;
    }

    @Override
    public void destroyPageFromContainer(ComponentContainer componentContainer, int i, Object obj) {
        if (componentContainer == null) {
            LogUtil.error(TAG, "destory item failed, container is null");
        } else if (obj instanceof Component) {
            componentContainer.removeComponent((Component) obj);
        }
    }

    @Override
    public boolean isPageMatchToObject(Component component, Object o) {
        return true;
    }
}
